package com.das.mechanic_base.widget;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.main.X3SelectBrandAdapter;
import com.das.mechanic_base.adapter.main.X3ShowBrandAdapter;
import com.das.mechanic_base.adapter.main.X3ShowCarmileAdapter;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.bean.main.CarBrandBean;
import com.das.mechanic_base.bean.main.HomeCarBean;
import com.das.mechanic_base.bean.main.MapCarBrandBean;
import com.das.mechanic_base.bean.main.UserBodyBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.X3StringUtils;

import java.util.ArrayList;
import java.util.List;

public class X3BottomCrmDialog extends X3BaseBottomSheetDialog implements View.OnClickListener, X3SelectBrandAdapter.IOnClickSelect {

    LinearLayout ll_Car_model;
    NestedScrollView nested_scroll_view;
    TextView tv_cancel;
    RecyclerView rl_brand;//品牌
    RecyclerView rl_Car_model;//车款
    RecyclerView rl_age_of_vehicle;//车龄
    RecyclerView rl_cars_miles;//里程
    Button btn_back;
    Button btn_next;
    private X3SelectBrandAdapter brandAdapter;
    private X3ShowBrandAdapter modelAdapter;
    private X3ShowCarmileAdapter vehicleAdapter;
    private X3ShowCarmileAdapter milesAdapter;
    private int sum = 0;//统计筛选条件的个数
    private long brandId = 0;//品牌ID
    private String brandName = "";//品牌名称
    private long modelId = 0;//车款ID
    private String modeName = "";//车款名称
    private List<String> carMileRangeList = new ArrayList<>();//里程本地集合
    private List<CarBrandBean> carBrandBean = new ArrayList<>();
    private List<String> carAgeRangeList = new ArrayList<>();// 车龄本地集合
    private List<CarBrandBean> carAgeBrandBean = new ArrayList<>();

    public X3BottomCrmDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        ll_Car_model = findViewById(R.id.ll_Car_model);
        nested_scroll_view = findViewById(R.id.nested_scroll_view);
        tv_cancel = findViewById(R.id.tv_cancel);
        rl_brand = findViewById(R.id.rl_brand);
        rl_Car_model = findViewById(R.id.rl_Car_model);
        rl_age_of_vehicle = findViewById(R.id.rl_age_of_vehicle);
        rl_cars_miles = findViewById(R.id.rl_cars_miles);
        btn_back = findViewById(R.id.btn_back);
        btn_next = findViewById(R.id.btn_next);
        tv_cancel.setOnClickListener(this);
        btn_back.setOnClickListener(this);
        btn_next.setOnClickListener(this);
        rl_brand.setLayoutManager(new GridLayoutManager(mContext, 3));
        rl_Car_model.setLayoutManager(new GridLayoutManager(mContext, 3));
        rl_age_of_vehicle.setLayoutManager(new GridLayoutManager(mContext, 3));
        rl_cars_miles.setLayoutManager(new GridLayoutManager(mContext, 3));
        //全部品牌
        brandAdapter = new X3SelectBrandAdapter(mContext);
        rl_brand.setAdapter(brandAdapter);
        brandAdapter.setiOnClickSelect(this);

        //车型
        modelAdapter = new X3ShowBrandAdapter(mContext);
        rl_Car_model.setAdapter(modelAdapter);
        modelAdapter.setiOnClickSelect(mapCarBrandBean -> {
            modelId = mapCarBrandBean.getId();
            modeName = mapCarBrandBean.getName();
            StatisticsSum();
        });

        //车领
        vehicleAdapter = new X3ShowCarmileAdapter(mContext);
        rl_age_of_vehicle.setAdapter(vehicleAdapter);
        vehicleAdapter.setiOnClickSelect((vehicleCarBrandBeans, position) -> {
            carAgeBrandBean = vehicleCarBrandBeans;
            //每次点击的之后都先清空本地的数据，从新获取
            carAgeRangeList.clear();
            /**
             * 车龄：：点击确定的时候，对选中里程进行筛选，如果选中将选中的里程添加到本地list，然后传递
             * 默认情况下，传null的list。查询全部。
             */
            for (CarBrandBean carAgBrandBean : carAgeBrandBean) {
                if (carAgBrandBean.isSelect()) {
                    String sum = carAgBrandBean.getValue();
                    carAgeRangeList.add(sum);
                }
            }
            StatisticsSum();
        });

        //行驶公里
        milesAdapter = new X3ShowCarmileAdapter(mContext);
        rl_cars_miles.setAdapter(milesAdapter);
        milesAdapter.setiOnClickSelect((carBrandBeans, position) -> {
            carBrandBean = carBrandBeans;
            //每次点击的之后都先清空本地的数据，从新获取
            carMileRangeList.clear();
            /**
             * 里程：：点击确定的时候，对选中里程进行筛选，如果选中将选中的里程添加到本地list，然后传递
             * 默认情况下，传null的list。查询全部。
             */
            for (CarBrandBean carBrandBean1 : carBrandBean) {
                if (carBrandBean1.isSelect()) {
                    String sum = carBrandBean1.getValue();
                    carMileRangeList.add(sum);
                }
            }
            StatisticsSum();
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_home_bottom_crm_dialog;
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_cancel) {
            dismiss();
        } else if (id == R.id.btn_back) {//第一步设置按钮样式
            changeBtnOne();

            //第二步：清空当前本地选中的数据,这里只有在点击确定按钮之后才清空，防止用户点击重置之后，直接点取消，还显示筛选之前的数据
            brandId = 0;
            brandName = "";
            modelId = 0;
            modeName = "";
            carMileRangeList.clear();
            carAgeRangeList.clear();
            sum = 0;
            StatisticsSum();
            //adapter清空数据，刷新视图
            if (brandAdapter != null) {
                brandAdapter.changeReset();
            }
            //，重置之后，车款隐藏
            ll_Car_model.setVisibility(View.GONE);
            if (modelAdapter != null) {
                modelAdapter.changeReset();
            }

            if (vehicleAdapter != null) {
                vehicleAdapter.changeReset();
            }
            if (milesAdapter != null) {
                milesAdapter.changeReset();
            }

            if (iOnSelectHome != null) {
                iOnSelectHome.iOnSelectReset();
            }
        } else if (id == R.id.btn_next) {
            dismiss();
            if (iOnSelectHome != null) {
                iOnSelectHome.iOnSelectHome(sum, brandId, brandName, modelId, modeName, carMileRangeList, carAgeRangeList);
            }
        }
    }

    IOnSelectHome iOnSelectHome;

    public void setiOnSelectHome(IOnSelectHome iOnSelectHome) {
        this.iOnSelectHome = iOnSelectHome;
    }

    public interface IOnSelectHome {
        //统计筛选的数量：statisticsSum；品牌的ID和名称：brandId、brandName；
        void iOnSelectHome(int statisticsSum, long brandId, String brandName, long modelId, String modeName, List<String> carMileRangeList, List<String> carAgeRangeList);

        //点击清空回掉
        void iOnSelectReset();

        //点击车辆品牌，请求车型接口
        void showmodelAdapter(long brandId, String brandName);
    }

    /**
     * 全部品牌
     *
     * @param mapCarBrandBeans
     * @param selectBrand
     */
    public void changeData(List<MapCarBrandBean> mapCarBrandBeans, String selectBrand) {
        if (brandAdapter != null) {
            brandAdapter.changeSelect(selectBrand, mapCarBrandBeans);
        }

        if (!X3StringUtils.isListEmpty(mapCarBrandBeans)) {
            for (MapCarBrandBean carBrandBean : mapCarBrandBeans) {
                if (selectBrand.equals(carBrandBean.getName())) {
                    brandId = carBrandBean.getId();
                    brandName = selectBrand;
                    ll_Car_model.setVisibility(View.VISIBLE);
                }
            }
            StatisticsSum();
        }
    }

    /**
     * 全部年款-(先选车品牌)
     *
     * @param mapCarBrandBeans
     * @param selectBrand
     */
    public void getShowCarStyleData(List<MapCarBrandBean> mapCarBrandBeans, String selectBrand) {
        if (modelAdapter != null) {
            if (mapCarBrandBeans == null && mapCarBrandBeans.size() == 0) {
                ll_Car_model.setVisibility(View.GONE);
            } else {
                if (!X3StringUtils.isListEmpty(mapCarBrandBeans)) {
                    for (MapCarBrandBean carBrandBean : mapCarBrandBeans) {
                        if (selectBrand.equals(carBrandBean.getName())) {
                            modelId = carBrandBean.getId();
                            modeName = selectBrand;
                        }
                    }
                    StatisticsSum();
                }
                ll_Car_model.setVisibility(View.VISIBLE);
                modelAdapter.changeSelect(selectBrand, mapCarBrandBeans);
            }
        }
    }

    /**
     * 车辆里程：逻辑说明
     *
     * @param carBrandBeans：返回的说有里程数据
     * @param carMileRange：选中的里程，多选   第一步：通过两次遍历，如果已经选中过里程，那么将当前选中里程的item状态设置为true状态，否则为false，方便在adapter中进行区分显示。
     *                                第二步：本地通过list记录返回的选中里程。目的是解决用户不再点击的情况，保留之前选中的状态。
     *                                第三步：只要点击过item，将本地的list数据清空，重新获取当前选中的里程数据。从新提交。
     */
    public void getshowCarMileRange(List<CarBrandBean> carBrandBeans, List<String> carMileRange) {
        if (milesAdapter != null) {
            if (carMileRange != null && carMileRange.size() > 0) {
                for (int i = 0; i < carBrandBeans.size(); i++) {
                    for (int j = 0; j < carMileRange.size(); j++) {
                        if (carBrandBeans.get(i).getValue().equals(carMileRange.get(j))) {
                            carBrandBeans.get(i).setSelect(true);
                            carMileRangeList.add(carBrandBeans.get(i).getValue());
                        }
                    }
                }
                StatisticsSum();
            }
            milesAdapter.changeSelect(carBrandBeans);
        }
    }

    /**
     * 车龄：逻辑说明同里程
     *
     * @param carBrandBeans：返回的所有里程数据
     * @param carMileRange：选中的车龄，多选   第一步：通过两次遍历，如果已经选中过车龄，那么将当前选中车龄的item状态设置为true状态，否则为false，方便在adapter中进行区分显示。
     *                                第二步：本地通过list记录返回的选中里程。目的是解决用户不再点击的情况，保留之前选中的状态。
     *                                第三步：只要点击过item，将本地的list数据清空，重新获取当前选中的里程数据。从新提交。
     */
    public void getShowCarAgeRange(List<CarBrandBean> carBrandBeans, List<String> carMileRange) {
        if (vehicleAdapter != null) {
            if (carMileRange != null && carMileRange.size() > 0) {
                for (int i = 0; i < carBrandBeans.size(); i++) {
                    for (int j = 0; j < carMileRange.size(); j++) {
                        if (carBrandBeans.get(i).getValue().equals(carMileRange.get(j))) {
                            carBrandBeans.get(i).setSelect(true);
                            carAgeRangeList.add(carBrandBeans.get(i).getValue());
                        }
                    }
                }
                StatisticsSum();
            }
            vehicleAdapter.changeSelect(carBrandBeans);
        }
    }

    @Override
    public void iOnClickSelectBrand(MapCarBrandBean carBrandBean) {
        this.brandId = carBrandBean.getId();
        brandName = carBrandBean.getName();
        //当点击车辆品牌的时候，将本地的车款信息清空，在点击车款的时候再去赋值
        ll_Car_model.setVisibility(View.VISIBLE);
        modelId = 0;
        modeName = "";
        StatisticsSum();
        if (iOnSelectHome != null) {
            iOnSelectHome.showmodelAdapter(brandId, brandName);
        }
    }

    /**
     * @param isClick=true?全部可点击：全部不可点击
     */
    public void changeBtn(boolean isClick) {
        btn_back.setEnabled(isClick);
        btn_next.setEnabled(isClick);
        btn_back.setTextColor(isClick ? Color.parseColor("#0077ff") : Color.parseColor("#C7C7C7"));
        btn_next.setBackgroundColor(isClick ? Color.parseColor("#0077ff") : Color.parseColor("#D5D5D5"));
    }

    /**
     * 点击重置按钮，重置置灰，确定按钮可点击
     */
    public void changeBtnOne() {
        btn_back.setEnabled(false);
        btn_next.setEnabled(true);
        btn_back.setTextColor(Color.parseColor("#D5D5D5"));
        btn_next.setBackgroundColor(Color.parseColor("#0077ff"));
    }

    /**
     * 如果四个筛选都是空，那么默认按钮走false
     * 否则重新计算四个筛选的数量
     */
    private void StatisticsSum() {
        if (brandId == 0 && modelId == 0 && carMileRangeList.size() == 0 && carAgeRangeList.size() == 0) {
            sum=0;
            btn_next.setText(mContext.getString(R.string.x3_apply_confirm));
        } else {
            int brandSum, modelSum;
            if (brandId == 0) {
                brandSum = 0;
            } else {
                brandSum = 1;
            }
            if (modelId == 0) {
                modelSum = 0;
            } else {
                modelSum = 1;
            }
            sum = brandSum + modelSum + carMileRangeList.size() + carAgeRangeList.size();
            changeBtn(true);
            NetWorkHttp.getApi().requestCarForMechanic(getCarBodyBean(new UserBodyBean()))
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .subscribe(new HttpCallBack<HomeCarBean>() {
                        @Override
                        protected void onDone(HomeCarBean homeCarBean) {
                            if(0 == homeCarBean.getTotal()){
                                btn_next.setText(mContext.getString(R.string.x3_crm_no_data_cimp));
                            }else {
                                if (1 == homeCarBean.getTotal()) {
                                    btn_next.setText(String.format(mContext.getString(R.string.x3_apply_time),homeCarBean.getTotal()));
                                }else {
                                    btn_next.setText(String.format(mContext.getString(R.string.x3_apply_times),homeCarBean.getTotal()));
                                }
                            }
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {

                        }
                    });
            Log.e("TAG", "=========" + brandSum + "=======" + modelSum + "=========" + carMileRangeList.size() + "======" + carAgeRangeList.size());
        }
    }

    /**
     * 车辆-获取车辆列表选中的
     *
     * @return
     */
    public UserBodyBean getCarBodyBean(UserBodyBean bodyBean) {
        bodyBean.setPageNum(1);
        bodyBean.setPageSize(20);
        bodyBean.setOnlyMe(true);

        //品牌ID、车款ID
        bodyBean.setCarBrandId(brandId);
        bodyBean.setCarStyleId(modelId);
        //行驶里程
        bodyBean.setCarMileRangeList(carMileRangeList);
        //车龄
        bodyBean.setCarAgeRangeList(carAgeRangeList);

        return bodyBean;
    }

}
